package fun.codedesign.jdk.lang.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射方法进行执行
 *
 * @author zengjian
 * @create 2018-03-13 17:38
 * @since 1.0.0
 */
public class TemplateReflect {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Template t = new Template();
        Method[] methods = t.getClass().getDeclaredMethods();
        String[] strArr = {"hello"};
        Method m1 = t.getClass().getDeclaredMethod("hi", String.class, Integer.class);
        m1.getParameterTypes();

        m1.isAnnotationPresent(Deprecated.class);

        for (Method method : methods) {
            method.setAccessible(true);
            if (method.getName().contains("hello")) {
                method.setAccessible(true);
                method.invoke(t, (Object)null);
                break;
            }
            if (method.getName().contains("do")) {
                // 这里因为Method方法中的args参数是一个变长数组，所以传一个数组参数时需要转换成一个Object参数
                // 否则会按照数组拆分成多个参数
                Object result = method.invoke(t, (Object) strArr);
                if (result instanceof String) {
                    System.out.println((String) result);
                }
            }
        }
    }
}
